import fpPromise, { type GetResult } from '@peng_kai/kit/libs/fingerprintjs';
import { createGlobalState } from '@peng_kai/kit/libs/vueuse';
import { aeg45sa48ahbwegew, md5Hash } from '~/utils/cipher';

export const useFingerprint = createGlobalState((immediate: boolean = true) => {
  const fingerprint = ref<GetResult | undefined>();

  async function getFingerprintAction() {
    try {
      const fp = await fpPromise.load();
      const r = await fp.get();
      fingerprint.value = r;
      return r;
    }
    catch (error) {
      fingerprint.value = void 0;
      return void 0;
    }
  }

  async function getDeviceInfo() {
    const r = fingerprint.value || await getFingerprintAction();
    if (!r)
      return '';
    return aeg45sa48ahbwegew(
      JSON.stringify({
        languages: r.components.languages.value?.join(','),
        platform: r.components.platform.value,
        screen_rolution: r.components.screenResolution.value?.join('x'),
        timezone: r.components.timezone.value,
        vendor: r.components.vendor.value,
        vendor_flavors: r.components.vendorFlavors.value?.join(','),
        visitor_id: r.visitorId,
      }),
    );
  }

  async function getDeviceInfoMD5() {
    const r = fingerprint.value || await getFingerprintAction();
    if (!r)
      return '';
    return md5Hash(
      JSON.stringify({
        languages: r.components.languages.value?.join(','),
        platform: r.components.platform.value,
        timezone: r.components.timezone.value,
        vendor: r.components.vendor.value,
        vendor_flavors: r.components.vendorFlavors.value?.join(','),
      }),
    );
  }

  immediate && getFingerprintAction();

  return { fingerprint, getFingerprintAction, getDeviceInfo, getDeviceInfoMD5 };
});
